package org.dei.perla.parser.expressions;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

public class ConstantFile extends ConstantUserDefined {
	
	private Byte[] data;
	private String filePath;

	public ConstantFile(String initializationString) throws ConstantCreationException{
		super("ConstantFile", initializationString);
		this.filePath = initializationString;
		File file = new File(initializationString);
		if (!file.exists()) {
			throw new ConstantCreationException("Il file " + initializationString + " non esiste!");
		}
		if (file.isDirectory()) {
			throw new ConstantCreationException("Impossibile leggere dal file " + initializationString + " in quanto e' una directory");
		}
		try {
			FileInputStream fis = new FileInputStream(file);
			BufferedInputStream bis = new BufferedInputStream(fis);
			ArrayList<Byte> dataArrayList = new ArrayList<Byte>();
			while (bis.available() != 0) {
				dataArrayList.add((byte)bis.read());
			}
			data = new Byte[dataArrayList.size()];
			data = dataArrayList.toArray(data);
			bis.close();
			fis.close();
		} catch (FileNotFoundException e) {
			throw new ConstantCreationException("Errore durante l'apertura del file " + initializationString + ", " + e.getMessage());
		} catch (IOException e) {
			throw new ConstantCreationException("Errore durante la lettura del file " + initializationString + ", " + e.getMessage());
		}
	}
	
	public Byte[] getValueBytes() {
		return data;
	}
	
	public ConstantBlob getValueBlob() {
		return new ConstantBlob(data);
	}
	
	public String toString() {
		StringBuffer toReturn = new StringBuffer("File: ");
		toReturn.append(filePath);
		toReturn.append(" [ ");
		for (int i = 0; i < data.length; i ++) {
			toReturn.append(data[i]);
			if (i != data.length - 1) {
				toReturn.append(", ");
			}
		}
		toReturn.append(" ]");
		
		return toReturn.toString();
	}
}
